﻿using System;
using System.Configuration;
using DynamicComparer;
using System.Collections.Generic;
using System.Web;
using System.Web.UI.WebControls;
using Shuba.Business;
using Shuba.Model;

namespace Shuba.Web.mobile
{
    public partial class branch_device_list : basePage
    {
        string msg = "";
        bool IsView, IsAdd, IsEdit, IsDelete, IsChecker;

        protected void Page_Load(object sender, EventArgs e)
        {
            this.Form.DefaultFocus = txtSearch.ClientID;
            this.Form.DefaultButton = btnSearch.UniqueID;

            string acl = GetUserAccess("MSTR_BRANCH_DEVICE");

            IsView = IsUserView(acl);
            IsAdd = IsUserAdd(acl);
            IsEdit = IsUserEdit(acl);
            IsDelete = IsUserDelete(acl);
            IsChecker = IsUserChecker(acl);

            if (!IsView)
            {
                msg = this.GetGlobalResourceObject("Messages", "NoPrivilege").ToString();
                AlertAndRedirect(msg, ResolveUrl(ConfigurationManager.AppSettings["default_url"]));
            }

            if (!IsPostBack)
            {
                InitSort();
                BindData();

                LabelTitle.Text = GetPageTitle("MSTR_BRANCH_DEVICE");

                btnAdd.Enabled = IsAdd;
                btnUpload.Enabled = IsAdd;
            }
        }

        private void BindData()
        {
            BranchDevice bl = new BranchDevice();
            List<BranchDeviceInfo> list = bl.GetList(txtSearch.Text);
            if (ViewState["SortEx"].ToString().Trim() != "")
            {
                string sort = sort = ViewState["SortEx"].ToString() + " " + ViewState["Sort"];
                DynamicComparer<BranchDeviceInfo> comparer = new DynamicComparer<BranchDeviceInfo>(sort);
                list.Sort(comparer);
            }

            gvList.DataSource = list;
            gvList.DataBind();

            bool commandVisible = IsEdit || IsDelete;
            if (!export)
                gvList.Columns[gvList.Columns.Count - 1].Visible = commandVisible;

            if (IsChecker)
            {
                BindApprovalData();
            }
        }
        bool export = false;

        protected void gvList_PageIndexChanging(object sender, System.Web.UI.WebControls.GridViewPageEventArgs e)
        {
            gvList.PageIndex = e.NewPageIndex;
            BindData();
        }

        protected void gvList_RowCommand(object sender, System.Web.UI.WebControls.GridViewCommandEventArgs e)
        {
            if (e.CommandArgument == null)
                return;

            string imei = e.CommandArgument.ToString();
            switch (e.CommandName)
            {
                case "Edit":
                    Response.Redirect("branch_device_add.aspx?a=ed&i=" + imei);
                    break;
                case "Remove":
                    string id = e.CommandArgument.ToString();
                    BranchDevice bl = new BranchDevice();

                    BranchDeviceInfo info = bl.Get(imei);
                    info.UpdateBy = HttpContext.Current.User.Identity.Name;
                    info.UpdateDate = ProcessingDate();
                    info.ActType = "DELETE";
                    try
                    {
                        bl.Save(info);
                        AddLog("DELETE", "DELETE BRANCH DEVICE");
                        Alert("Delete success!");
                        BindData();
                    }
                    catch (Exception ex)
                    {
                        msg = ex.Message.ToString();
                        ErrBox.Visible = true;
                        ErrMsg.Text = msg;
                    }

                    //if (msg == "") RestartPage();
                    break;
            }
        }

        protected void gvList_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                if (export)
                {
                    e.Row.Cells[0].Text = "'" + e.Row.Cells[0].Text;
                }
                else
                {
                    LinkButton btnEdit = (LinkButton)e.Row.FindControl("btnEdit");
                    LinkButton btnDelete = (LinkButton)e.Row.FindControl("btnDelete");

                    btnEdit.Enabled = IsEdit;


                    btnDelete.Enabled = IsDelete;
                    if (!IsDelete) btnDelete.OnClientClick = "";
                }

                /*
                if (e.Row.Cells[gvList.Columns.Count - 2].Text == "" || e.Row.Cells[gvList.Columns.Count - 2].Text == "1")
                {
                    e.Row.Cells[gvList.Columns.Count - 2].Text = "Active";

                    e.Row.ForeColor = System.Drawing.Color.Black;
                    e.Row.Font.Bold = false;
                }
                else
                {
                    e.Row.Cells[gvList.Columns.Count - 2].Text = "Inactive";

                    e.Row.ForeColor = System.Drawing.Color.Red;
                    e.Row.Font.Bold = true;

                    e.Row.Cells[e.Row.Cells.Count - 1].ForeColor = System.Drawing.Color.Black;
                    e.Row.Cells[e.Row.Cells.Count - 1].Font.Bold = false;
                */
            }
        }

        protected void gvList_Sorting(object sender, System.Web.UI.WebControls.GridViewSortEventArgs e)
        {
            SortDirection(e.SortExpression, e.SortDirection.ToString());
            ViewState["SortEx"] = e.SortExpression;
            gvList.PageIndex = 0;
            BindData();
        }

        /*======================================
                APPROVAL GRID START HERE
         =======================================
         */
        private void BindApprovalData()
        {
            BranchDevice bl = new BranchDevice();
            List<BranchDeviceInfo> list = bl.GetListApproval(HttpContext.Current.User.Identity.Name);
            if (ViewState["SortEx"].ToString().Trim() != "")
            {
                string sort = sort = ViewState["SortEx"].ToString() + " " + ViewState["Sort"];
                DynamicComparer<BranchDeviceInfo> comparer = new DynamicComparer<BranchDeviceInfo>(sort);
                list.Sort(comparer);
            }
            ApprovalGrid.DataSource = list;
            ApprovalGrid.DataBind();

            ApprovalPnl.Visible = list.Count > 0;
        }

        protected void ApprovalGrid_PageIndexChanging(object sender, System.Web.UI.WebControls.GridViewPageEventArgs e)
        {
            ApprovalGrid.PageIndex = e.NewPageIndex;
            BindApprovalData();
        }

        protected void ApprovalGrid_Sorting(object sender, System.Web.UI.WebControls.GridViewSortEventArgs e)
        {
            SortDirection(e.SortExpression, e.SortDirection.ToString());
            ViewState["SortEx"] = e.SortExpression;
            ApprovalGrid.PageIndex = 0;
            BindApprovalData();
        }

        protected void btnApprove_Click(object sender, EventArgs e)
        {
            foreach (GridViewRow row in ApprovalGrid.Rows)
            {
                CheckBox chkItemSelect = (CheckBox)row.FindControl("chkItemSelect");
                string imei = ApprovalGrid.DataKeys[row.RowIndex].Value.ToString();
                if (chkItemSelect.Checked)
                {
                    Approve(imei, true);
                }
            }
            msg = this.GetGlobalResourceObject("Messages", "ApproveAlert").ToString();
            BindData();
            Alert(msg);
        }

        protected void btnReject_Click(object sender, EventArgs e)
        {
            foreach (GridViewRow row in ApprovalGrid.Rows)
            {
                CheckBox chkItemSelect = (CheckBox)row.FindControl("chkItemSelect");

                string imei = ApprovalGrid.DataKeys[row.RowIndex].Value.ToString();
                if (chkItemSelect.Checked)
                {
                    Approve(imei, false);
                }
            }
            msg = this.GetGlobalResourceObject("Messages", "NoApprove").ToString();
            BindData();
            Alert(msg);
        }

        private void Approve(string imei, bool IsApprove)
        {
            BranchDevice bl = new BranchDevice();
            BranchDeviceInfo bi = bl.GetApprovalByID(imei);
            bi.UpdateBy = HttpContext.Current.User.Identity.Name;
            bi.UpdateDate = ProcessingDate();

            if (IsApprove)
            {
                bl.Approve(imei, bi.ActType);
                AddLog("APPROVAL", "APPROVE BRANCH DEVICE");
            }
            else
            {
                bl.Reject(imei);
                AddLog("APPROVAL", "REJECT BRANCH DEVICE");
            }
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            BindData();
        }

        protected void btnExport_Click(object sender, EventArgs e)
        {
            export = true;
            gvList.AllowPaging = false;
            gvList.Columns.RemoveAt(3);
            BindData();
            GridViewExportUtil.Export("branch_devices.xls", gvList);
        }
    }
}
